package com.huang.CAS.LongAdder;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.concurrent.atomic.LongAdder;

/*
*       LongAdd .sum()   base+cell[]  分散热点 cell最大根据CPU核数
*                   内部  主要 Long  base 计数  cell单元格
*                   原理 并发小 base足以  并发大起来了 创建cell数组
*                   根据线程id 算出hash值 以某种方式映射到cell数组的下标加入其中   最后进行累加
*
*       AtomicIntger .get（）一直对base进行叠加
*               内部CAS一直自旋
*
*
*
* */
public class dyDemo {
    private static volatile  Integer threadNum=50;
    private  static volatile  Integer times=1000000;

    public static void main(String[] args) throws InterruptedException {

        CountDownLatch countDownLatch = new CountDownLatch(threadNum);
        LongAccumulator longAccumulator = new LongAccumulator((x, y) -> {
           return x + y;
        }, 0);
        long l3 = System.currentTimeMillis();
        for (int i = 0; i < threadNum; i++) {
            new Thread(()->{
                for (int aLong = 0; aLong < times; aLong++) {
                    longAccumulator.accumulate(1);
                }
                countDownLatch.countDown();
            }).start();
        }

        countDownLatch.await();
        long l4 = System.currentTimeMillis();
        System.out.println(l4 - l3+"次数"+longAccumulator.longValue());


        //2
        CountDownLatch countDownLatch2 = new CountDownLatch(threadNum);
        long l1 = System.currentTimeMillis();
        LongAdder adder = new LongAdder();
        for (int i2 = 0; i2 < threadNum; i2++) {
            new Thread(()->{

                try {
                    for (Integer i1 = 0; i1 < times; i1++) {
                        adder.add(1);

                    }
                } finally {
                    countDownLatch2.countDown();
                }
            }).start();
        }
        countDownLatch2.await();
        long l2 = System.currentTimeMillis();
        System.out.println(l2-l1+"次数"+adder.longValue());

    }
}
